import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Input, message, Modal, Form, Select, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { listPostByPage, updatePost, deletePost, getPostById, addPost } from '@/api/communityPostController';
import { listCategories } from '@/api/communityCategoryController';
import { listCommunityTags } from '@/api/communityTagController';
import { 
  PlusOutlined, 
  SearchOutlined, 
  VerticalAlignTopOutlined, 
  FireOutlined, 
  StarOutlined 
} from '@ant-design/icons';
import { Editor } from '@bytemd/react';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight';
import 'bytemd/dist/index.css';
import 'highlight.js/styles/vs.css';
import { withAdminAuth } from '@/components/AdminAuth';

interface PostData {
  id: string;
  title: string;
  content: string;
  categorycode: string;
  tagcode: number;
  likecount: number;
  commentcount: number;
  viewcount: number;
  auditstatus: number;
  userVo: {
    nickName: string;
    avatarUrl: string;
  };
  createtime: string;
  updatetime: string;
}

interface CategoryData {
  categorycode: string;
  categorynamezh: string;
}

interface TagData {
  tagcode: number;
  tagnamezh: string;
}

const statusMap = {
  0: { text: '待审核', color: 'default' },
  1: { text: '已通过', color: 'success' },
  2: { text: '已拒绝', color: 'error' },
};

const getTagStyle = (tagCode: number) => {
  switch (tagCode) {
    case 1: // 置顶
      return 'bg-red-100 text-red-600';
    case 2: // 热门
      return 'bg-rose-100 text-rose-600';
    case 3: // 推荐
      return 'bg-yellow-100 text-yellow-600';
    default:
      return 'bg-blue-100 text-blue-600';
  }
};

const renderTagIcon = (tagCode: number) => {
  switch (tagCode) {
    case 1: // 置顶
      return <VerticalAlignTopOutlined className="ml-1 text-red-500" />;
    case 2: // 热门
      return <FireOutlined className="ml-1 text-rose-500" />;
    case 3: // 推荐
      return <StarOutlined className="ml-1 text-yellow-500" />;
    default:
      return null;
  }
};

const plugins = [
  gfm(),
  highlight(),
];

const editorConfig = {
  mode: 'split',
  locale: {
    write: '编辑',
    preview: '预览',
    writeOnly: '仅编辑',
    previewOnly: '仅预览',
    splitView: '分屏预览'
  }
};

// 添加样式
const editorWrapperStyle: React.CSSProperties = {
  '.bytemd-fullscreen': {
    zIndex: 1500 // 设置一个比 Modal 更高的 z-index
  }
};

// 添加上传配置
const uploadConfig = {
  UPLOAD_URL: 'http://localhost:8081/api/file/upload',
  IMAGE_TYPE: 'community_post_pic',
  VIDEO_TYPE: 'community_post_video'
};

function PostManagement() {
  const [postList, setPostList] = useState<PostData[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(8);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentPost, setCurrentPost] = useState<PostData | null>(null);
  const [categories, setCategories] = useState<CategoryData[]>([]);
  const [tags, setTags] = useState<TagData[]>([]);
  const [modalType, setModalType] = useState<'edit' | 'add'>('edit');
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [editorValue, setEditorValue] = useState('');

  // 获取分类和标签列表
  const fetchCategoriesAndTags = async () => {
    try {
      const [categoriesRes, tagsRes] = await Promise.all([
        listCategories(),
        listCommunityTags()
      ]);
      
      if (categoriesRes.code === 200) {
        setCategories(categoriesRes.data);
      }
      if (tagsRes.code === 200) {
        setTags(tagsRes.data);
      }
    } catch (error) {
      message.error('获取分类或标签列表失败');
    }
  };

  // 获取帖子列表
  const fetchPosts = async () => {
    setLoading(true);
    try {
      const values = await searchForm.validateFields()
        .catch(() => ({}));
      
      const searchParams = {
        current,
        pageSize,
        title: values.title || '',
        createuser: values.createuser || '',
        categorycode: values.categorycode || ''
      };

      const res = await listPostByPage(searchParams);
      if (res.code === 200) {
        setPostList(res.data.records);
        setTotal(parseInt(res.data.total));
      }
    } catch (error) {
      message.error('获取帖子列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchPosts();
    fetchCategoriesAndTags();
  }, [current, pageSize]);

  // 处理新增
  const handleAdd = () => {
    setModalType('add');
    form.resetFields();
    setEditorValue('');
    setCurrentPost(null);
    setIsModalVisible(true);
  };

  // 处理编辑
  const handleEdit = async (record: PostData) => {
    try {
      const res = await getPostById({ id: record.id });
      if (res.code === 200) {
        setModalType('edit');
        setCurrentPost(res.data);
        setEditorValue(res.data.content || '');
        form.setFieldsValue({
          ...res.data,
          content: res.data.content || ''
        });
        setIsModalVisible(true);
      }
    } catch (error) {
      message.error('获取帖子详情失败');
    }
  };

  // 处理删除
  const handleDelete = async (id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这篇帖子吗？',
      onOk: async () => {
        try {
          const res = await deletePost({ id });
          if (res.code === 200) {
            message.success('删除成功');
            fetchPosts();
          }
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      let res;
      if (modalType === 'edit') {
        res = await updatePost({
          ...values,
          id: currentPost?.id,
        });
      } else {
        res = await addPost(values);
      }

      if (res.code === 200) {
        message.success(modalType === 'edit' ? '更新成功' : '新增成功');
        setIsModalVisible(false);
        fetchPosts();
      }
    } catch (error) {
      message.error(modalType === 'edit' ? '更新失败' : '新增失败');
    }
  };

  // 修改文件上传处理函数
  const handleUpload = async (files: File[]) => {
    const results: Array<{ url: string }> = [];
    
    for (const file of files) {
      const formData = new FormData();
      formData.append('file', file);
      const biz = file.type.startsWith('video/') 
        ? uploadConfig.VIDEO_TYPE 
        : uploadConfig.IMAGE_TYPE;
      formData.append('biz', biz);

      try {
        const response = await fetch(uploadConfig.UPLOAD_URL, {
          method: 'POST',
          body: formData,
          credentials: 'include',
        });

        const result = await response.json();
        if (result.code === 200) {
          results.push({
            url: result.data
          });
        } else {
          message.error(`文件上传失败: ${result.message}`);
        }
      } catch (error) {
        message.error('文件上传失败');
        console.error('Upload error:', error);
      }
    }

    return results;
  };

  const columns: ColumnsType<PostData> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
    },
    {
      title: '阅读量',
      dataIndex: 'viewcount',
      key: 'viewcount',
      width: 100,
    },
    {
      title: '点赞量',
      dataIndex: 'likecount',
      key: 'likecount',
      width: 100,
    },
    {
      title: '评论量',
      dataIndex: 'commentcount',
      key: 'commentcount',
      width: 100,
    },
    {
      title: '分类',
      dataIndex: 'categorycode',
      key: 'categorycode',
      width: 120,
      render: (code) => {
        const category = categories.find(c => c.categorycode === code);
        return category?.categorynamezh || code;
      }
    },
    {
      title: '标签',
      dataIndex: 'tagcode',
      key: 'tagcode',
      width: 120,
      render: (code) => {
        const tag = tags.find(t => t.tagcode === code);
        return (
          <div className={`inline-flex items-center px-2 py-1 rounded-md ${getTagStyle(code)}`}>
            {tag?.tagnamezh || code}
            {renderTagIcon(code)}
          </div>
        );
      }
    },
    {
      title: '状态',
      dataIndex: 'auditstatus',
      key: 'auditstatus',
      width: 100,
      render: (status) => (
        <Tag color={statusMap[status]?.color || 'default'}>
          {statusMap[status]?.text || '未知'}
        </Tag>
      ),
    },
    {
      title: '创建者',
      dataIndex: ['userVo', 'nickName'],
      key: 'creator',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      key: 'createtime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="p-4">
      <div className="mb-4">
        <Form
          form={searchForm}
          layout="inline"
          onFinish={fetchPosts}
        >
          <Form.Item name="title">
            <Input 
              placeholder="帖子标题" 
              onPressEnter={() => searchForm.submit()}
            />
          </Form.Item>
          <Form.Item name="categorycode">
            <Select
              placeholder="选择分类"
              allowClear
              style={{ width: 200 }}
              options={categories.map(cat => ({
                label: cat.categorynamezh,
                value: cat.categorycode
              }))}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleAdd} icon={<PlusOutlined />}>
              新增帖子
            </Button>
          </Form.Item>
        </Form>
      </div>

      <Table 
        columns={columns} 
        dataSource={postList}
        rowKey="id"
        loading={loading}
        pagination={{
          total,
          current,
          pageSize,
          onChange: (page, size) => {
            setCurrent(page);
            setPageSize(size);
          },
        }}
      />

      <Modal
        title={modalType === 'edit' ? '编辑帖子' : '新增帖子'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={1200}
        style={{ top: 20 }}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{ content: editorValue }}
        >
          <Form.Item name="title" label="标题" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="content" label="内容" rules={[{ required: true }]}>
            <div className="bytemd-wrapper">
              <Editor
                plugins={plugins}
                value={editorValue}
                onChange={(v) => {
                  setEditorValue(v);
                  form.setFieldsValue({ content: v });
                }}
                mode="split"
                locale={{
                  write: '编辑',
                  preview: '预览',
                  writeOnly: '仅编辑',
                  previewOnly: '仅预览',
                  splitView: '分屏预览'
                }}
                uploadImages={handleUpload}
              />
            </div>
          </Form.Item>
          <Form.Item name="categorycode" label="分类" rules={[{ required: true }]}>
            <Select
              options={categories.map(cat => ({
                label: cat.categorynamezh,
                value: cat.categorycode
              }))}
            />
          </Form.Item>
          <Form.Item name="tagcode" label="标签" rules={[{ required: true }]}>
            <Select
              options={tags.map(tag => ({
                label: tag.tagnamezh,
                value: tag.tagcode
              }))}
            />
          </Form.Item>
          {modalType === 'edit' && (
            <Form.Item name="auditstatus" label="状态" rules={[{ required: true }]}>
              <Select
                options={Object.entries(statusMap).map(([value, { text }]) => ({
                  label: text,
                  value: parseInt(value)
                }))}
              />
            </Form.Item>
          )}
          
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {modalType === 'edit' ? '更新' : '提交'}
              </Button>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default withAdminAuth(PostManagement);